<?php
defined('BASEPATH') or exit('No direct script access allowed');
require APPPATH.'libraries/ApiController.php';
class Menus extends ApiController
{
	public function __construct()
	{
	    parent::__construct();
	}

	function index(){

	}

	
	public function list_by_page(){
		$token=123;//$this->verifyToken();
		if($token){
			$list=$user=$this->db->select("*")->order_by("order","asc")->get("auth_menu")->result_array();
			
			//echo "<pre>";
			//print_r($list);
			
			$menus=$this->buildTree($list,-1);
			$this->WRITE("code",1);
			$this->WRITE("list",$menus);
			$this->WRITE("msg","success");
			$this->RESPONSE();
		}
	}

	protected function buildTree($cats,$pid=-1){
		$tree=[];
		foreach($cats as $cat){
			if($cat["pid"]==$pid){
					$children=$this->buildTree($cats,$cat["mid"]);
					usort($children,function($a,$b){
						return $a["order"]<=$b["order"];
					});
					if($children){
						$cat["children"]=$children;
					}else{
						$cat["children"]=[];
					}
				$tree[]=$cat;
			}
		}
		usort($tree,function($a,$b){
			return $a["order"]<=$b["order"];
		});
		return $tree;
	} 
	
	
	public function detail(){
		$token=$this->verifyToken();
			if($token){
				$data=$this->getKeys([
				  ['menuid',True,"菜单id"]],'post');
				$row=$this->db->where("mid",$data["menuid"])->select("*")->get("auth_menu")->row_array();
 
				$this->WRITE("code",1);
				$this->WRITE("detail",$row);
				$this->WRITE("msg","success");
				$this->RESPONSE();
			}
		
	}
	
	public function update(){
		$token=$this->verifyToken();
		if($token){
			$data=$this->getKeys([
			  ['menuid',True,"菜单id"],
			  ['title',True,"菜单名称"],
			  ['enable',True,"启用禁用状态"],
			  ['key',False,"菜单标识",""],
			  ['path',False,"路径",""],
			  ['order',False,"排序",0]
			  ],'post');
			$data["mid"]=$data["menuid"];
			unset($data["menuid"]);
			$res=$this->db->where("mid",$data["mid"])->update("auth_menu",$data);
			if($res){
				$this->WRITE("code",1);
				$this->WRITE("msg","编辑菜单成功!");
				$this->RESPONSE();
			}else{
				$this->WRITE("code",0);
				$this->WRITE("msg","编辑菜单失败!");
				$this->RESPONSE();
			} 
		}
	}
	
	

}